from flask import Blueprint, request, jsonify, render_template
from datetime import datetime
import random
from app import db
from app.models import Robot, Task

# 创建蓝图
main_bp = Blueprint('main', __name__)

# 主页路由 - 提供前端界面
@main_bp.route('/')
def index():
    """渲染主界面"""
    return render_template('index.html')

# 机器人相关API
@main_bp.route('/api/robots', methods=['GET'])
def get_robots():
    """获取机器人列表"""
    # 获取查询参数
    status = request.args.get('status')
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    
    # 构建查询
    query = Robot.query
    if status:
        query = query.filter_by(status=status)
    
    # 分页查询
    pagination = query.order_by(Robot.created_at.desc()).paginate(page=page, per_page=per_page)
    robots = pagination.items
    
    # 构建返回结果
    return jsonify({
        'success': True,
        'data': [robot.to_dict() for robot in robots],
        'pagination': {
            'total': pagination.total,
            'pages': pagination.pages,
            'page': page,
            'per_page': per_page,
            'has_next': pagination.has_next,
            'has_prev': pagination.has_prev
        }
    })

@main_bp.route('/api/robots/<int:robot_id>', methods=['GET'])
def get_robot(robot_id):
    """获取单个机器人详情"""
    robot = Robot.query.get_or_404(robot_id)
    return jsonify({
        'success': True,
        'data': robot.to_dict()
    })

@main_bp.route('/api/robots', methods=['POST'])
def create_robot():
    """创建新机器人"""
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['robot_id', 'name', 'type', 'status']
    for field in required_fields:
        if field not in data or not data[field]:
            return jsonify({
                'success': False,
                'error': 'Missing required field',
                'message': f'Field "{field}" is required'
            }), 400
    
    # 检查机器人ID是否已存在
    if Robot.query.filter_by(robot_id=data['robot_id']).first():
        return jsonify({
            'success': False,
            'error': 'Duplicate robot ID',
            'message': f'Robot with ID "{data["robot_id"]}" already exists'
        }), 400
    
    # 创建新机器人
    new_robot = Robot(
        robot_id=data['robot_id'],
        name=data['name'],
        type=data['type'],
        description=data.get('description', ''),
        ip_address=data.get('ip_address', ''),
        port=data.get('port'),
        protocol=data.get('protocol', ''),
        battery_capacity=data.get('battery_capacity'),
        max_load=data.get('max_load'),
        move_speed=data.get('move_speed'),
        status=data['status'],
        last_active=datetime.utcnow()
    )
    
    try:
        db.session.add(new_robot)
        db.session.commit()
        
        # 为新机器人创建一个初始任务（模拟数据）
        if data.get('create_default_task', True):
            default_task = Task(
                robot_id=new_robot.id,
                task_name=f'初始化任务 - {new_robot.name}',
                progress=0,
                status='pending'
            )
            db.session.add(default_task)
            db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Robot created successfully',
            'data': new_robot.to_dict()
        }), 201
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': 'Database error',
            'message': str(e)
        }), 500

@main_bp.route('/api/robots/<int:robot_id>', methods=['PUT'])
def update_robot(robot_id):
    """更新机器人信息"""
    robot = Robot.query.get_or_404(robot_id)
    data = request.get_json()
    
    try:
        # 更新字段
        if 'name' in data:
            robot.name = data['name']
        if 'type' in data:
            robot.type = data['type']
        if 'description' in data:
            robot.description = data['description']
        if 'ip_address' in data:
            robot.ip_address = data['ip_address']
        if 'port' in data:
            robot.port = data['port']
        if 'protocol' in data:
            robot.protocol = data['protocol']
        if 'battery_capacity' in data:
            robot.battery_capacity = data['battery_capacity']
        if 'max_load' in data:
            robot.max_load = data['max_load']
        if 'move_speed' in data:
            robot.move_speed = data['move_speed']
        if 'status' in data:
            robot.status = data['status']
            # 如果状态变为在线，更新最后活动时间
            if data['status'] == 'online':
                robot.last_active = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Robot updated successfully',
            'data': robot.to_dict()
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': 'Database error',
            'message': str(e)
        }), 500

@main_bp.route('/api/robots/<int:robot_id>', methods=['DELETE'])
def delete_robot(robot_id):
    """删除机器人"""
    robot = Robot.query.get_or_404(robot_id)
    
    try:
        # 删除关联的任务
        Task.query.filter_by(robot_id=robot_id).delete()
        # 删除机器人
        db.session.delete(robot)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Robot deleted successfully'
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': 'Database error',
            'message': str(e)
        }), 500

@main_bp.route('/api/robots/statistics', methods=['GET'])
def get_robot_statistics():
    """获取机器人统计数据"""
    # 总机器人数量
    total = Robot.query.count()
    
    # 按状态统计
    online_count = Robot.query.filter_by(status='online').count()
    offline_count = Robot.query.filter_by(status='offline').count()
    maintenance_count = Robot.query.filter_by(status='maintenance').count()
    
    # 按类型统计
    type_stats = db.session.query(
        Robot.type, 
        db.func.count(Robot.id)
    ).group_by(Robot.type).all()
    
    type_dict = {
        'cleaning': 0,
        'transport': 0,
        'inspection': 0,
        'delivery': 0
    }
    for robot_type, count in type_stats:
        if robot_type in type_dict:
            type_dict[robot_type] = count
    
    # 任务统计
    total_tasks = Task.query.count()
    running_tasks = Task.query.filter_by(status='running').count()
    completed_tasks = Task.query.filter_by(status='completed').count()
    
    # 计算任务完成率
    completion_rate = round((completed_tasks / total_tasks * 100) if total_tasks > 0 else 0, 1)
    
    # 活跃度趋势数据（模拟最近8小时）
    hours = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
    online_trend = [random.randint(12, 20) for _ in range(8)]
    task_trend = [random.randint(8, 16) for _ in range(8)]
    
    return jsonify({
        'success': True,
        'data': {
            'summary': {
                'total_robots': total,
                'online_robots': online_count,
                'offline_robots': offline_count,
                'maintenance_robots': maintenance_count,
                'total_tasks': total_tasks,
                'running_tasks': running_tasks,
                'completed_tasks': completed_tasks,
                'completion_rate': completion_rate
            },
            'type_distribution': type_dict,
            'activity_trend': {
                'hours': hours,
                'online_robots': online_trend,
                'active_tasks': task_trend
            }
        }
    })

# 任务相关API
@main_bp.route('/api/tasks', methods=['GET'])
def get_tasks():
    """获取任务列表"""
    robot_id = request.args.get('robot_id')
    status = request.args.get('status')
    
    query = Task.query
    if robot_id:
        query = query.filter_by(robot_id=robot_id)
    if status:
        query = query.filter_by(status=status)
    
    tasks = query.order_by(Task.updated_at.desc()).all()
    
    return jsonify({
        'success': True,
        'data': [task.to_dict() for task in tasks]
    })

@main_bp.route('/api/tasks/<int:task_id>/progress', methods=['PUT'])
def update_task_progress(task_id):
    """更新任务进度"""
    task = Task.query.get_or_404(task_id)
    data = request.get_json()
    
    if 'progress' not in data:
        return jsonify({
            'success': False,
            'error': 'Missing required field',
            'message': 'Field "progress" is required'
        }), 400
    
    progress = int(data['progress'])
    # 确保进度在0-100之间
    progress = max(0, min(100, progress))
    
    try:
        task.progress = progress
        # 如果进度达到100，自动设置为已完成
        if progress == 100:
            task.status = 'completed'
        # 如果进度大于0且状态是待执行，设置为运行中
        elif progress > 0 and task.status == 'pending':
            task.status = 'running'
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Task progress updated successfully',
            'data': task.to_dict()
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': 'Database error',
            'message': str(e)
        }), 500

@main_bp.route('/api/robots/generate-id', methods=['GET'])
def generate_robot_id():
    """生成唯一的机器人ID"""
    from datetime import datetime
    import random
    
    year = datetime.now().year
    # 生成随机3位数
    while True:
        random_num = random.randint(100, 999)
        robot_id = f'RB-{year}-{random_num}'
        # 检查是否已存在
        if not Robot.query.filter_by(robot_id=robot_id).first():
            return jsonify({
                'success': True,
                'data': {
                    'robot_id': robot_id
                }
            })
    